package org.simp.core.body;

import org.apache.log4j.Logger;

import com.google.protobuf.GeneratedMessage;
import com.google.protobuf.InvalidProtocolBufferException;

/**
 * @author zhuhaitao at 2014-5-30
 *
 * 
 */
public abstract class AbstractBody<T,M extends GeneratedMessage> implements SimpBody{
	protected static final Logger log = Logger.getLogger(AbstractBody.class);

	protected T body;
	protected M msg ;
	
	public AbstractBody(){}
	
	public AbstractBody(T body){
		this.body = body;
	}
	
	public AbstractBody(M msg){
		this.msg = msg;
	}
	
	@Override
	public byte[] encode() {
		if(body !=null)
			msg = parseFrom(body);
		return toBytes();
	}

	@Override
	public void decode(byte[] data) {
		try{
			msg = parseFrom(data);
			body = format(msg);
		}catch (InvalidProtocolBufferException e) {
			log.error(" decode body error ",e);
		}
		
	}
	/**
	 * 将bean转换为pbMsg
	 * @param entity
	 * @return
	 *  @Author zhuhaitao at 2014年6月17日
	 *
	 */
	public abstract M parseFrom(T body);
	/**
	 * 从字节数组中初始化pbMsg
	 * @param data
	 * @return
	 * @throws InvalidProtocolBufferException
	 *  @Author zhuhaitao at 2014年6月17日
	 *
	 */
	public abstract M parseFrom(byte[] data) throws InvalidProtocolBufferException ;
	
	/**
	 * 将pbMsg转换为bean
	 * @param msg
	 * @return
	 *  @Author zhuhaitao at 2014年6月17日
	 *
	 */
	public abstract T format(M msg);
	
	/**
	 * 根据protoBean返回byte数组，编码
	 * @return
	 * @author zhuhaitao at 2014-5-30
	 */
	public  byte[] toBytes(){
		if( msg == null){
			return new byte[0];
		}
		return msg.toByteArray();
	}

	public T getBody() {
		if(body == null && msg!=null)
			body = format(msg);
		
		return body;
	}

	public void setBody(T body) {
		this.body = body;
	}

	public M getMsg() {
		if(msg == null && body !=null)
			msg = parseFrom(body);		
		return msg;
	}

	public void setMsg(M msg) {
		this.msg = msg;
	}
	
	
}
